package com.sias.Loli.util;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Properties;
import java.util.Random;

public class VerificationCode {
    public static void  getVF(HttpSession session, HttpServletResponse response) {
        Properties p=new Properties();
        p.setProperty("kaptcha.border","yes");
        //设置字体颜色
        p.setProperty("kaptcha.textproducer.font.color","255,85,0");
        p.setProperty("kaptcha.textproducer.font.size","24");
        //设置图片的宽
        p.setProperty("kaptcha.image.width","100");
        //设置图片的高
        p.setProperty("kaptcha.image.height","38");
        DefaultKaptcha ka = new DefaultKaptcha();
        ka.setConfig(new Config(p));
        BufferedImage image = ka.createImage(create(session));
        try {
            ImageIO.write(image,"png",response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
/*
创建验证码的随机文本
 */
    private static String create(HttpSession session){
        int result=0;//记录表达式的结果
        Random random=new Random();
        //随机生成第一位数字 2位以内
        int num1=random.nextInt(99)+1;
        //随机生成第一位数字 2位以内
        int num2=random.nextInt(99)+1;
        //随机生成 运算符 0+ 1- 2X
        int y=random.nextInt(3);
        StringBuffer buffer=new StringBuffer();
        buffer.append(num1);
        switch (y){
            case 0:{buffer.append(" + ");
                result=num1+num2;
            }break;
            case 1:{buffer.append(" - ");
                result=num1-num2;
            }break;
            default:{buffer.append(" * ");
                result=num1*num2;
            }break;
        }
        buffer.append(num2+" = ");
        System.out.println("验证码"+result);
        session.setAttribute("code",Integer.toString(result));
        return buffer.toString();
    }
}


